package com.chencs.biz.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chencs.biz.Common;
import com.chencs.biz.product.controller.FavoritesController;
import com.chencs.biz.product.mapper.FavoritesMapper;
import com.chencs.biz.product.model.SimpleProductModel;
import com.chencs.utils.MoneyUtils;
import com.chencs.utils.StringUtils;
import com.chencs.vo.biz.product.FavoritesModel;
import com.chencs.vo.biz.product.KeyModel;
import com.chencs.vo.biz.product.ProductModel;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.UatmTbkItem;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.request.TbkUatmFavoritesGetRequest;
import com.taobao.api.request.TbkUatmFavoritesItemGetRequest;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.taobao.api.response.TbkUatmFavoritesGetResponse;
import com.taobao.api.response.TbkUatmFavoritesItemGetResponse;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by fangzehua on 2017/6/30.
 */
@Service
@Transactional
public class FavoritesService {
    org.slf4j.Logger logger = LoggerFactory.getLogger(FavoritesService.class);
    @Autowired
    private FavoritesMapper favoritesMapper;
    /**
     * 同步商品选品库
     */
    public  boolean syncFavorites(){
        TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl+Common.favorites,Common.appKey,Common.appSecre);
        TbkUatmFavoritesGetRequest req = new TbkUatmFavoritesGetRequest();
        req.setPageNo(1l);
        req.setPageSize(200l);
        req.setFields("favorites_title,favorites_id,type");
        try {
            TbkUatmFavoritesGetResponse response = client.execute(req);
            String data = response.getBody();
          // favoritesMapper.delAllFavorites();
            FavoritesModel model = null;
            for(int i=0;i<response.getResults().size();i++){
                model = new FavoritesModel();
                if(favoritesMapper.findFavoritesModelById(response.getResults().get(i).getFavoritesId().toString())==null){
                    model.setCode(response.getResults().get(i).getFavoritesId().toString());
                    model.setTitle(response.getResults().get(i).getFavoritesTitle().toString());
                    model.setType(response.getResults().get(i).getType().toString());
                    model.setDescs(response.getResults().get(i).getFavoritesTitle());
                    favoritesMapper.insertFavorites(model);
                }

            }
            return  true;
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }


    public FavoritesModel findFavoritesByCode(String code){
        return  favoritesMapper.findFavoritesModelById(code);
    }



    public void updateFavoritesByModel(FavoritesModel model){
        favoritesMapper.updateFavoritesByModel(model);
    }




    public List<FavoritesModel> getFavoriteList(){

        return favoritesMapper.getFavoriteList();
    }


    public void clear_pro(){

         favoritesMapper.clear_pro();
    }


    /**
     * 同步商品选品库
     */
    public  int syncFavoritesProduct(String code){
        FavoritesModel favoritesModel = favoritesMapper.findFavoritesModelById(code);
        logger.debug("syncFavoritesProduct",favoritesModel.toString());
        if(favoritesModel.getCid()==null){
            return -1;
        }else {
            TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl + Common.favorites_item, Common.appKey, Common.appSecre);
            TbkUatmFavoritesItemGetRequest req = new TbkUatmFavoritesItemGetRequest();
            req.setPageNo(1l);
            req.setPageSize(300l);
            req.setAdzoneId(Common.adzoneId);
            req.setFavoritesId(Long.parseLong(code)); //click_url,
            req.setFields("coupon_click_url,coupon_end_time,coupon_start_time,coupon_info,click_url,num_iid,title,pict_url,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick,shop_title,zk_final_price_wap,tk_rate,status,type");
            try {
                TbkUatmFavoritesItemGetResponse response = client.execute(req);
                ProductModel productModel = null;
                List<UatmTbkItem> results = response.getResults();

                if (results==null){
                    return  - 3;
                }
                for (int i = 0; i < results.size(); i++) {
                    if (results.get(i).getStatus() == 1) {
                        productModel = new ProductModel();
                        productModel.setCid(favoritesModel.getCid());
                        productModel.setCpid(favoritesModel.getCpid());
                        productModel.setPid(results.get(i).getNumIid().toString());
                        productModel.setProurl(results.get(i).getClickUrl());
                        productModel.setProimg(results.get(i).getPictUrl());
                        productModel.setPname(results.get(i).getTitle().replace(" ", ""));
                        productModel.setShopname(results.get(i).getShopTitle());
                        productModel.setCommissionrate(results.get(i).getTkRate());
                        productModel.setCommission(MoneyUtils.commissionrate(results.get(i).getZkFinalPrice(), results.get(i).getTkRate()));
                        productModel.setPrice(MoneyUtils.m2(Double.parseDouble(results.get(i).getZkFinalPrice())-StringUtils.getCoupon(results.get(i).getCouponInfo()))+"");
                        productModel.setOldprice(results.get(i).getReservePrice());
                        productModel.setCouponname(results.get(i).getCouponInfo());
                        productModel.setCouponurl(results.get(i).getCouponClickUrl());
                        productModel.setCouponcode(StringUtils.getCoupon(results.get(i).getCouponInfo())+"");
                        productModel.setStarttime(results.get(i).getCouponStartTime());
                        productModel.setEndtime(results.get(i).getCouponEndTime());
                        productModel.setSource(results.get(i).getProvcity());
                        productModel.setFlag("0");
                        productModel.setTag("0");
                        productModel.setOrderno("0");
                        productModel.setFavorites(code);
                        productModel.setSales(results.get(i).getVolume().toString());
                        productModel.setUsertype(results.get(i).getUserType().toString());
                        favoritesMapper.insertProduct(productModel);
                    }
                }




                getProuduct(code,favoritesModel);

                favoritesMapper.updateFavorites(code);
                return 0;
            } catch (ApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return -2;
            }
        }
    }


    public void getProuduct(String code,FavoritesModel favoritesModel ){
            TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl + Common.favorites_item, Common.appKey, Common.appSecre);
            TbkUatmFavoritesItemGetRequest req = new TbkUatmFavoritesItemGetRequest();
            req.setPageNo(2l);
            req.setPageSize(300l);
            req.setAdzoneId(Common.adzoneId);
            req.setFavoritesId(Long.parseLong(code)); //click_url,
            req.setFields("coupon_click_url,coupon_end_time,coupon_start_time,coupon_info,click_url,num_iid,title,pict_url,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick,shop_title,zk_final_price_wap,tk_rate,status,type");
            try {
                TbkUatmFavoritesItemGetResponse response = client.execute(req);
                ProductModel productModel = null;
          //      System.out.print(response.getBody());
                List<UatmTbkItem> results = response.getResults();
                for (int i = 0; i < results.size(); i++) {
                    if (results.get(i).getStatus() == 1) {
                        productModel = new ProductModel();
                        productModel.setCid(favoritesModel.getCid());
                        productModel.setCpid(favoritesModel.getCpid());
                        productModel.setPid(results.get(i).getNumIid().toString());
                        productModel.setProurl(results.get(i).getClickUrl());
                        productModel.setProimg(results.get(i).getPictUrl());
                        productModel.setPname(results.get(i).getTitle().replace(" ", ""));
                        productModel.setShopname(results.get(i).getShopTitle());
                        productModel.setCommissionrate(results.get(i).getTkRate());
                        productModel.setCommission(MoneyUtils.commissionrate(results.get(i).getZkFinalPrice(), results.get(i).getTkRate()));
                        productModel.setPrice(MoneyUtils.m2(Double.parseDouble(results.get(i).getZkFinalPrice()) - StringUtils.getCoupon(results.get(i).getCouponInfo())) + "");
                        productModel.setOldprice(results.get(i).getReservePrice());
                        productModel.setCouponname(results.get(i).getCouponInfo());
                        productModel.setCouponurl(results.get(i).getCouponClickUrl());
                        productModel.setCouponcode(StringUtils.getCoupon(results.get(i).getCouponInfo()) + "");
                        productModel.setStarttime(results.get(i).getCouponStartTime());
                        productModel.setEndtime(results.get(i).getCouponEndTime());
                        productModel.setSource(results.get(i).getProvcity());
                        productModel.setFlag("0");
                        productModel.setTag("0");
                        productModel.setOrderno("0");
                        productModel.setFavorites(code);
                        productModel.setSales(results.get(i).getVolume().toString());
                        productModel.setUsertype(results.get(i).getUserType().toString());
                        favoritesMapper.insertProduct(productModel);
                    }
                }
            } catch (Exception e) {
                    e.printStackTrace();
            }



    }


    public SimpleProductModel getSimpleProduct(String pid){
        SimpleProductModel model = null;
        TaobaoClient client = new DefaultTaobaoClient(Common.apiUrl+Common.pro_item,Common.appKey,Common.appSecre);
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setFields("click_url,num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url");
        req.setPlatform(2L);
        req.setNumIids(pid);
        TbkItemInfoGetResponse rsp = null;
        try {
            rsp = client.execute(req);
            model = new SimpleProductModel();
            model.setnTbkItem(rsp.getResults().get(0));
           // System.out.println(rsp.getBody());
            model.setModel(favoritesMapper.findProductByPid(pid));

            return model;
        } catch (ApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }



    }



    public List<ProductModel> getProduct(){

        return favoritesMapper.getProduct();
    }



    public boolean setHostKey(){

        String str = "";
        try {
            org.jsoup.nodes.Document res = Jsoup.connect("http://openapi.qingtaoke.com/hot?app_key=8qwMgSJx&v=1.0&t=3").timeout(10000).ignoreContentType(true).post();
            str = res.body().text();
          //  System.out.println(str);
            JSONObject jsonObject = JSONObject.parseObject(str);
            if(jsonObject.getString("er_code").equals("10000")){
             try {

                 favoritesMapper.delhotKey();
                 JSONArray jsonArray = jsonObject.getJSONArray("data");
                 KeyModel keyModel = null;
                 for (int i =0;i<jsonArray.size();i++){
                     String name = jsonArray.getJSONObject(i).getString("word");
                     String total = jsonArray.getJSONObject(i).getString("total");
                     keyModel = new KeyModel();
                     keyModel.setKeyword(name);
                     keyModel.setHeat(total);
                     favoritesMapper.insertHotKey(keyModel);
                 }
             }catch (Exception e){
                    e.printStackTrace();
                    return false;
             }

            }

        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        return true;
    }


}
